﻿(function() {
	sharpRegistry.panes["default.folder"] = function(url, folder, displayElementId, clickCallback, extendedConfig) {
		this.folderItem = folder;
		this.folderUrl = url;
		this.displayElement = (el = document.id(displayElementId)) ? el : new Element('div', {id: 'item-listing-div'});
		this.itemListingDivId = extendedConfig && extendedConfig.has('listingDivId') ? extendedConfig['listingDivId'] : 'item-listing-div';
		this.itemListingListId = extendedConfig && extendedConfig.has('listingListId') ? extendedConfig['listingListId'] : 'item-listing';
		this.parentElementId = extendedConfig && extendedConfig.has('parentElementId') ? extendedConfig['parentElementId'] : 'block1';
		this.trackPane = extendedConfig && extendedConfig.has('trackPane') ? extendedConfig['trackPane'] : true;
		this.applicationUrl = extendedConfig && extendedConfig.has('applicationUrl') ? extendedConfig['applicationUrl'] : sharpbar.applicationUrl ? sharpbar.applicationUrl : window.location.href;
		this.embedListInDiv = extendedConfig && extendedConfig.has('embedListInDiv') ? extendedConfig['embedListInDiv'] : true;
		this.paneHeader = new Element('div', { 'id': 'block1header' });
		this.paneFooter = new sharpRegistry.panes['default.folder.footer']('block1footer');
		
		this.toHtml = function() {
			var baseUrl = url.charAt(url.length-1) == '/' ? url.slice(0, url.length-1) : url;
			function makeClickHandler(urlSegment, mimeType, fullUrl) {
				return clickCallback ? function() { clickCallback(baseUrl, urlSegment, fullUrl); } : function() {
					if (fullUrl) {
						url = fullUrl;
					} else if (urlSegment) {
						var lastChar = baseUrl.charAt(baseUrl.length - 1),
							uri = new URI(baseUrl);
						uri.clearData();
						url = lastChar == "/" ? uri.toString() : lastChar == "#" ? baseUrl.slice(baseUrl.length - 1) + "/" : uri.toString() + "/";
						url = url + urlSegment.slice(urlSegment.lastIndexOf('/') + 1);
					} else {
						url = baseUrl.slice(0, baseUrl.slice(0, baseUrl.length).lastIndexOf('/'));
					}

					var itemInfoElement;
					if (sharpRegistry.activePanes.item) {
						itemInfoElement = document.id(sharpRegistry.activePanes.item.displayElementId);
					}
					else {
						itemInfoElement = document.id('content');
					}

					modal = document.id('browse-folder-popover');
					if (modal)
						modal.destroy();
						
					if (itemInfoElement) {
						itemInfoElement.empty();
					}

					if (mimeType == 'application/x-folder') {
						sharpbar.browser.openByUrl(url, ['D:displayname', 'mc:mimetype', 'mc:resourceprovider', 'mc:version']);
					} else {
						sharpbar.browser.openByUrl(url);
					}
					updateBreadCrumbs(url);
				};
			}
				
			var itemListing = new Element('ul', { id: this.itemListingListId }),
				xml = this.folderItem,
				children = xml.getElementsByTagName('D:response'),
				directoryRows = new Array(),
				fileRows = new Array();
					
			if (this.parentElementId == 'block1') {
				var directoryHref = (hrefs = children[0].getElementsByTagName('D:href')) ? hrefs[0].firstChild.nodeValue : null,
					directoryHrefParts = directoryHref.split('/'),
					newrow = new Element('a', {
						html: 'Inventory',
						href: '#',
						events: {
							click: makeClickHandler(null, 'application/x-folder', this.applicationUrl)
						}
					});
				this.paneHeader.grab(new Element('img', {
						'src': sharpbar.mediaUrl + "/Resources/images/folder_orange.png", 
						'alt': 'Click here to display folder in the table editor.',
						'target': sharpbar.applicationUrl + directoryHref,
						'events': {
							'click': function() {
								var targetUrl = this.getAttribute('target'),
									tableEditor = new TableEditor(targetUrl),
									title = targetUrl.slice(sharpbar.applicationUrl.length);
								document.id('content').empty();
								tableEditor.renderIntoElement('content', title);
							}
						},
						'styles': {
							'cursor': 'pointer',
							'padding-left': '34px',
							'padding-right': '2px'
						}
					}
				));
				this.paneHeader.grab(newrow);
				
				if (directoryHref != '/') {
					var currentUrl = this.applicationUrl;
					directoryHrefParts.each(function(part){
						if (part) {
							this.paneHeader.appendText(' / ');
							this.paneHeader.grab(new Element('a', {
								html: part,
								href: '#',
								events: {
									click: makeClickHandler('/' + part, 'application/x-folder', currentUrl + '/' + part)
								}
							}));
							currentUrl = currentUrl + '/' + part;
						}
					}, this);
				}
			} else {
				var cleanUrl = this.applicationUrl.charAt(this.applicationUrl.length - 1) == "#" ? this.applicationUrl.slice(0, -1) : this.applicationUrl;
				// Make both urls end with a "/" or not end with a "/" as a position final "/" should not make two URLs unequal
				cleanUrl = cleanUrl.charAt(cleanUrl.length - 1) == "/" && baseUrl.charAt(baseUrl.length - 1) != "/" ? cleanUrl.slice(0, -1) : cleanUrl;
				if (baseUrl != cleanUrl) {
					directoryRows.push(newrow = new Element('li', {
						'class': "parent-directory-item"
					}).grab(new Element('a', {
						html: 'Previous Directory',
						href: '#',
						events: {
							click: makeClickHandler(null, 'application/x-folder')
						}
					})));
				}
			}
			
			for (var i = 1; i < children.length; i++) {
				child = children[i];
				if (child) {
					var childUrlSegment = child.getElementsByTagName('D:href')[0].firstChild.nodeValue;

					// Get the mimetype
					var mimeType = (els = child.getElementsByTagName('mc:mimetype')) && els[0].firstChild ? els[0].firstChild.nodeValue : null;
					var displayName = (els = child.getElementsByTagName('D:displayname')) && els[0].firstChild ? els[0].firstChild.nodeValue : null;
					// TODO: No mimetype? Think about how to "guess" the mimetype. 
					if (!displayName)
						continue;
						
					if (mimeType == "application/x-folder") {
						newrow = new Element('li', { 'class': "directory-item" });
						newrow.grab(new Element('img', {
								'src': sharpbar.mediaUrl + "/Resources/images/folder_orange.png", 
								'alt': 'Click here to display folder in the table editor.',
								'target': sharpbar.applicationUrl + childUrlSegment,
								'events': {
									'click': function() {
										var targetUrl = this.getAttribute('target'),
											tableEditor = new TableEditor(targetUrl),
											title = targetUrl.slice(sharpbar.applicationUrl.length);
										document.id('content').empty();
										tableEditor.renderIntoElement('content', title);
									}
								},
								'styles': {
									'cursor': 'pointer'
								}
							})
						);
					} else {
						newrow = new Element('li', { 'class': "file-item" });
						newrow.grab(new Element('img', {'src': sharpbar.mediaUrl + "/Resources/images/misc_doc.png" }));
					}
					newrow.grab(
						new Element('a', {
							html: displayName,
							href: '#',
							events: {
								click: makeClickHandler(childUrlSegment, mimeType)
							}
						})
					);
					mimeType == "application/x-folder" ? directoryRows.push(newrow) : fileRows.push(newrow);
				}
			}
			
			itemListing.adopt(directoryRows.sort(sortItemListing).concat(fileRows.sort(sortItemListing)));
			return itemListing;
		};
		this.display = function() {
			var pane = this.toHtml();
			if (pane) {
				if ((el = document.id(this.itemListingListId))) {
					if (this.embedListInDiv)
						this.paneHeader.replaces('block1header');
						
					pane.replaces(el);
				}
				else {
					var itemDiv = new Element('div', { id: this.itemListingDivId });
					
					if (this.embedListInDiv) {
						var scrollPane = document.id('scrollpane');	
						if (scrollPane) {
							scrollPane.empty();
						} else {
							scrollPane = new Element('div', { 'id': 'scrollpane' });
						}
						scrollPane.grab(itemDiv);
						this.paneHeader.inject(this.parentElementId);
						itemDiv.grab(pane);
						scrollPane.grab(itemDiv);
						scrollPane.inject(this.parentElementId);
						this.paneFooter.inject(this.parentElementId);
					} else {
						itemDiv.grab(pane);
						this.paneHeader.inject(this.parentElementId);
						itemDiv.inject(this.parentElementId);
					}
				}
				
				if (this.trackPane) 
					sharpRegistry.activePanes.folder = this;
					
				this.resize();
			}
		};
		this.resize = function() {
			resizeFolder();
			if(!sharpRegistry.activePanes.item)
				resizeContent();
		};
	};
})();